<template>
  <div class="min-h-screen bg-gradient-to-br from-orange-50 to-amber-100">
    <div class="container mx-auto px-4 py-8">
      <!-- 头部导航 -->
      <div class="mb-8">
        <h1 class="text-4xl font-bold text-gray-800 mb-4">思维导图</h1>
      </div>

      <!-- 思维导图列表 -->
      <div v-if="!selectedXmind">
        <!-- 加载状态 -->
        <div v-if="loading" class="flex items-center justify-center py-12">
          <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-orange-500"></div>
          <span class="ml-3 text-gray-600">正在加载思维导图列表...</span>
        </div>
        
        <!-- 文件列表 -->
        <div v-else-if="xmindFiles.length > 0" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 max-w-6xl mx-auto">
          <div
            v-for="xmind in xmindFiles"
            :key="xmind.name"
            class="bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow duration-300 cursor-pointer transform hover:scale-105"
            @click="selectXmind(xmind)"
          >
            <div class="p-6">
              <div class="flex items-center mb-3">
                <svg class="w-8 h-8 text-orange-500 mr-3" fill="currentColor" viewBox="0 0 20 20">
                  <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
                <h3 class="text-xl font-semibold text-gray-800">{{ xmind.title }}</h3>
              </div>
              <p class="text-gray-600 text-sm">{{ xmind.name }}</p>
            </div>
          </div>
        </div>
        
        <!-- 空状态 -->
        <div v-else class="text-center py-12">
          <svg class="w-16 h-16 text-gray-400 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
          </svg>
          <p class="text-gray-600">暂无思维导图文件</p>
        </div>
      </div>

      <!-- 思维导图内容 -->
      <div v-if="selectedXmind" class="bg-white rounded-lg shadow-lg p-8">
        <div class="mb-6 flex items-center justify-between">
          <h2 class="text-2xl font-bold text-gray-800">{{ selectedXmind.title }}</h2>
          <div class="flex items-center space-x-4">
            <button
              @click="goBack"
              class="px-4 py-2 bg-orange-500 hover:bg-orange-600 text-white rounded-lg font-medium transition-colors"
            >
              返回列表
            </button>
          </div>
        </div>
        
        <!-- XMind 查看器 -->
        <div class="h-[calc(100vh-12rem)] border border-gray-300 rounded-lg overflow-hidden relative">
          <!-- 加载提示覆盖层 -->
          <div v-if="loadingXmind" class="absolute inset-0 bg-white bg-opacity-90 flex items-center justify-center z-10">
            <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-orange-500"></div>
            <span class="ml-3 text-gray-600">加载中，请稍等...</span>
          </div>
          <div ref="xmindContainer" class="w-full h-full"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted } from 'vue'
import { XMindEmbedViewer } from 'xmind-embed-viewer'

interface XmindFile {
  name: string
  title: string
  path: string
}

const selectedXmind = ref<XmindFile | null>(null)
const xmindContainer = ref<HTMLElement | null>(null)
const xmindFiles = ref<XmindFile[]>([])
const loading = ref(true)
const loadingXmind = ref(false)
let viewer: any = null

// 获取xmind文件列表
const loadXmindFiles = async () => {
  try {
    loading.value = true
    // 从后端API动态获取xmind文件列表
    const response = await fetch('/api/xmind-files')
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const files = await response.json()
    console.log('后端返回的文件列表:', files)
    console.log('环境变量 VITE_STATIC_BASE_URL:', import.meta.env.VITE_STATIC_BASE_URL)
    
    // 将相对路径转换为完整的静态资源URL
    xmindFiles.value = files.map(file => {
      console.log('原始路径:', file.path)
      console.log('VITE_STATIC_BASE_URL:', import.meta.env.VITE_STATIC_BASE_URL)
      
      if (file.path.startsWith('/public/')) {
        const pathWithoutPublic = file.path.replace('/public', '')
        console.log('去掉/public后的路径:', pathWithoutPublic)
        const newPath = `${import.meta.env.VITE_STATIC_BASE_URL}${pathWithoutPublic}`
        console.log('最终拼接的路径:', newPath)
        return {
          ...file,
          path: newPath
        }
      } else {
        console.log('路径不以/public/开头，保持原样:', file.path)
        return {
          ...file,
          path: file.path
        }
      }
    })
  } catch (error) {
    console.error('加载XMind文件列表失败:', error)
    // 如果API调用失败，使用备用的硬编码列表
    const fallbackFileNames = [
      '0.0教学日历.xmind',
      '1.0引导.xmind',
      '1.1前端深化维度.xmind', 
      '1.2大前端.xmind',
      '1.3前端技术演化史：从文档互联到体验工程化.xmind',
      '1.4前端技术演化史：从文档互联到体验工程化时间轴.xmind',
      '1.7前端开发框架分类.xmind'
    ]
    
    xmindFiles.value = fallbackFileNames.map(fileName => ({
      name: fileName,
      title: fileName.replace('.xmind', ''),
      path: `${import.meta.env.VITE_STATIC_BASE_URL}/xmind/${fileName}`
    }))
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadXmindFiles()
})

const selectXmind = async (xmind: XmindFile) => {
  selectedXmind.value = xmind
  loadingXmind.value = true
  
  await nextTick()
  
  if (xmindContainer.value) {
    // 清理之前的查看器
    if (viewer) {
      // xmind-embed-viewer 没有 destroy 方法，直接清空容器
      xmindContainer.value.innerHTML = ''
    }
    
    try {
      // 创建新的查看器
      viewer = new XMindEmbedViewer({
        el: xmindContainer.value
      })
      
      // 获取 XMind 文件并加载
      console.log('XMind文件信息:', xmind)
      console.log('请求路径:', xmind.path)
      console.log('环境变量 VITE_STATIC_BASE_URL:', import.meta.env.VITE_STATIC_BASE_URL)
      const response = await fetch(xmind.path)
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      const arrayBuffer = await response.arrayBuffer()
      await viewer.load(arrayBuffer)
      
      // 加载完成，隐藏加载提示
      loadingXmind.value = false
    } catch (error) {
      console.error('加载 XMind 文件失败:', error)
      loadingXmind.value = false
      if (xmindContainer.value) {
        xmindContainer.value.innerHTML = `<div class="flex items-center justify-center h-full text-red-600">加载失败: ${error instanceof Error ? error.message : '未知错误'}</div>`
      }
    }
  }
}

const goBack = () => {
  if (viewer && xmindContainer.value) {
    xmindContainer.value.innerHTML = ''
    viewer = null
  }
  selectedXmind.value = null
}
</script>

<style scoped>
/* XMind 查看器的基本样式 */
:deep(.xmind-embed-viewer) {
  width: 100% !important;
  height: 100% !important;
}

:deep(iframe) {
  width: 100% !important;
  height: 100% !important;
  border: none !important;
}

:deep(.xmind-embed-viewer canvas) {
  width: 100% !important;
  height: 100% !important;
}

:deep(.xmind-embed-viewer svg) {
  width: 100% !important;
  height: 100% !important;
}
</style>